from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.core.cache import cache


from .models import Area


class ProvinceAreasView(View):

    def get(self, request):

        # TODO： 读取缓存
        province_list = cache.get('province_list')  # 读到的数据 or None

        if not province_list:
            # 没有读到缓存数据，才需要到mysql中读取
            # 业务数据处理  ---> 过滤省信息构建响应参数
            try:
                provinces = Area.objects.filter(parent=None)
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '服务器内部错误'}, status=400, json_dumps_params={'ensure_ascii': False})

            province_list = [{'id': province.id, 'name': province.name} for province in provinces]

            # TODO：写入缓存
            cache.set('province_list', province_list, 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list}, status=200, json_dumps_params={'ensure_ascii': False})


class SubAreasView(View):

    def get(self, request, pk):

        sub_data = cache.get(f"sub_area_{pk}")

        if not sub_data:
            """缓存无数据，在mysql读取"""
            # 业务处理 --> 过滤子级行政区信息
            try:
                parent = Area.objects.get(id=pk)
                subs = parent.subs.all()
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '服务器内部错误'}, status=400, json_dumps_params={'ensure_ascii': False})

            subs_list = [{'id': sub.id, 'name': sub.name} for sub in subs]

            # 构建响应参数
            sub_data = {
                'id': parent.id,
                'name': parent.name,
                'subs': subs_list,
            }

            # TODO：写缓存 --> {"sub_arear_340000"：[{...}]}
            cache.set(f"sub_area_{parent.id}", sub_data, 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data}, status=200, json_dumps_params={'ensure_ascii': False})




















